package com.wondersgroup.hs.mobile.report.support.submitJob;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fr.base.Parameter;
import com.fr.data.JobValue;
import com.fr.data.TotalSubmitJob;
import com.fr.script.Calculator;
import com.wondersgroup.hs.mobile.nursing.rpc.dto.request.CommitReportSubmitReq;
import com.wondersgroup.hs.mobile.nursing.rpc.dto.response.ReportSubmitRsp;
import com.wondersgroup.hs.mobile.nursing.rpc.service.ReportService;
import com.wondersgroup.hs.mobile.nursing.rpc.utils.ClientServiceFactory;
import com.wondersgroup.hs.mobile.report.support.exception.StatusAndMessageError;

import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by zarra on 2016/12/29.
 */
public class NursingDocTotalSubmitJob extends TotalSubmitJob {

    static public final int rowIndex = 0;

    static public final String KeyServiceURL   = "__KeyServiceURL__";
    static public final String KeyTemplateCode = "__KeyTemplateCode__";
    static public final String KeyDocumentID   = "__KeyDocumentID__";
    static public final String KeyNurseID      = "__KeyNurseID__";
    static public final String KeyPatientID    = "__KeyPatientID__";

    public List<String> allColumnNames(Data data){
        List<String> result = new LinkedList<>();
        for (int i=0;i<data.getColumnCount();i++){
            result.add(data.getColumnName(i));
        }

        return result;
    }

    public Integer indexForColumnName(String name,Data data){
        int index = -1;
        for (int i=0;i<data.getColumnCount();i++){
            String n = data.getColumnName(i);
            if (n.equals(name)){
                index = i;
                break;
            }
        }
        return index;
    }

    public Object valueForColumnName(String name,Data data){
        int index = indexForColumnName(name,data);
        if (index >=0){
            Object v = data.getValueAt(rowIndex,index);
            if (v instanceof JobValue){
                JobValue jobValue = (JobValue) v;
                v = jobValue.getValue();
            }

            if (v instanceof Parameter){
                Parameter p = (Parameter) v;
                v = p.getValue();
            }

            return v;
        }else{
            return null;
        }
    }

    public Map<String,Object> getJobContext(Data data){
        Map<String,Object> map = new HashMap();

        List<String> columns = allColumnNames(data);

        for (String c : columns){
            map.put(c,valueForColumnName(c,data));
        }

        return map;
    }

    public CommitReportSubmitReq createRequest(Data data){
        Map<String,Object> context = getJobContext(data);


        String templateCode = context.get(KeyTemplateCode).toString();
        String documentID = context.get(KeyDocumentID).toString();
        String nurseID = context.get(KeyNurseID).toString();
        String patientID = context.get(KeyPatientID).toString();


        CommitReportSubmitReq req
                = new CommitReportSubmitReq(templateCode,documentID,patientID,nurseID);

        ObjectMapper objectMapper = new ObjectMapper();

        for (String key :context.keySet()){
            if (!key.startsWith("__")){
                Object v = context.get(key);
                try {
                    String stringValue = objectMapper.writeValueAsString(v);
                    req.putValue(key,stringValue);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }

        return req;

    }

    @Override
    protected void doTotalJob(Data data, Calculator calculator) throws Exception {
        Object urlValue = valueForColumnName(KeyServiceURL,data);
        if (urlValue != null){
            String url = urlValue.toString();


            CommitReportSubmitReq req = createRequest(data);

            ReportService reportService = ClientServiceFactory.service(ReportService.class,new URL(url));
            ReportSubmitRsp rsp = reportService.doSubmit(req);

            if (rsp.getStatus()< 0){
                throw new StatusAndMessageError(rsp.getStatus(),rsp.getMessage());
            }

        }
        else {
            throw new NullPointerException("URL can't be null");
        }

    }
}
